package com.inspur.resourcequery;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;
import org.kobjects.base64.Base64;

import android.app.ActionBar;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.inspur.common.BaseActivity;
import com.inspur.common.domain.RequestInfo;
import com.inspur.common.utils.URLManager;
import com.inspur.resourcequery.model.ResData;

public class SiteActivity  extends BaseActivity   implements SensorEventListener {
		ActionBar actionBar;
		// Sensor管理器
		private SensorManager mSensorManager = null;
		// 震动
		// 两次检测的时间间隔
		private static final int UPTATE_INTERVAL_TIME = 70;
		// 上次检测时间
		private long lastUpdateTime;
		private Vibrator mVibrator = null;
		private TextView tv;
		private TextView txt_map;
		private ImageView img_shake;
		private String lac;
		private String ci;
		private String equipid = "";
		private String useraccount;
		private String distance;
		private TableLayout resdetail_layout = null;
		private LinearLayout content_layout = null;
		public LocationClient mLocationClient = null;
		public BDLocationListener myListener = new MyLocationListener();
		double latitude;
		double longitude;
		double gps_Lat;
		double gps_Lon;
		public ResData models;
		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_resdetail);
			
			actionBar = super.getActionBar();
			actionBar.setTitle("附近站点");
			actionBar.setDisplayHomeAsUpEnabled(true);//设置显示箭头图标
//			actionBar.setIcon(this.getResources().getDrawable(R.drawable.));
//			actionBar.setDisplayUseLogoEnabled(false);
			actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
	       
			mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
			mLocationClient.registerLocationListener(myListener); // 注册监听函数
			LocationClientOption option = new LocationClientOption();
			option.setOpenGps(true);
			option.setAddrType("no");// 返回的定位结果包含地址信息
			option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
			option.setScanSpan(50000);// 设置发起定位请求的间隔时间为5000ms
			option.disableCache(true);// 禁止启用缓存定位
			option.setPoiNumber(5); // 最多返回POI个数
			option.setPoiDistance(1000); // poi查询距离
			option.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息
			mLocationClient.setLocOption(option);
			mLocationClient.start();
			if (mLocationClient != null && mLocationClient.isStarted()){
				mLocationClient.requestLocation();
			}
			SharedPreferences sysInfo = getSharedPreferences("inspur_rss_info", 0);
			distance = sysInfo.getString("btssize_txt", "");
			if (distance == null || distance.equals("")) {
				distance = "500";
			}
			tv = (TextView) this.findViewById(R.id.txt_shake);
			txt_map = (TextView) this.findViewById(R.id.txt_map);
			txt_map.setVisibility(8);
			img_shake = (ImageView) this.findViewById(R.id.img_shake);
			// resdetail_layout = (TableLayout) findViewById(R.id.resdetail_layout);
			content_layout = (LinearLayout) findViewById(R.id.content_layout);
			mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
			mVibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			img_shake.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					loadData();
				}
			});
			txt_map.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Bundle bundle = new Bundle();
					bundle.putSerializable("data", models);
					Intent intent = new Intent();
					intent.setClass(SiteActivity.this, ResDetailActivity.class);
					intent.putExtras(bundle);
					startActivity(intent);
				}
			});
		}
		private void loadData() {
			try{
				RequestInfo req = new RequestInfo();
				req.context = SiteActivity.this;
				req.requestUrl = URLManager.URL + URLManager.RES_QUERYINITCONDITION;
				req.params="1";
			// 就一个普通个的url请求封装成Client而已
			super.getDataFromServer(req, new DataCallback<String>() {
				@Override
				public void processData(String paramObject) {
					System.out.println("paramObject:" + paramObject);
					try{
						JSONObject object = new JSONObject(paramObject);
						System.out.println(object);
						Double lon1 = Double.parseDouble(new String(Base64.decode(object.getString("x"))));
						Double lat1 = Double.parseDouble(new String(Base64.decode(object.getString("y"))));
						System.out.println("转换出来的百度坐标经度:" + lon1 + "纬度:" + lat1);
						// 这里的就是GPS坐标 经过下面算法转换 基本上合真实的GPS坐标相差无几
						gps_Lat = latitude * 2 - lat1;
						gps_Lon = longitude * 2 - lon1;
						System.out.println("算法转算后的百度坐标经度:" + gps_Lon + "纬度:" + gps_Lat);
					}catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
					}
				}

				@Override
				public void getDataFailed() {
					// 这里仅作演示，实际请求失败后怎么操作根据实际情况来看

				}

			}, SiteActivity.this);
			// 获取请求后数据
			}catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}
		class MyLocationListener implements BDLocationListener {
			@Override
			public void onReceiveLocation(BDLocation location) {
				if (location == null)
					return;
				latitude = location.getLatitude();
				longitude = location.getLongitude();
				StringBuffer sb = new StringBuffer(256);
				sb.append("time : ");
				sb.append(location.getTime());
				sb.append("\nerror code : ");
				sb.append(location.getLocType());
				sb.append("\nlatitude : ");
				sb.append(location.getLatitude());
				sb.append("\nlontitude : ");
				sb.append(location.getLongitude());
				sb.append("\nradius : ");
				sb.append(location.getRadius());
				if (location.getLocType() == BDLocation.TypeGpsLocation) {
					sb.append("\nspeed : ");
					sb.append(location.getSpeed());
					sb.append("\nsatellite : ");
					sb.append(location.getSatelliteNumber());
				} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
					sb.append("\naddr : ");
					sb.append(location.getAddrStr());
				}
				System.out.println(sb.toString());
				transBaidu(location.getLatitude(),location.getLongitude());
				mLocationClient.stop();
			}

			public void onReceivePoi(BDLocation poiLocation) {
				if (poiLocation == null) {
					return;
				}
				latitude = poiLocation.getLatitude();
				longitude = poiLocation.getLongitude();
				StringBuffer sb = new StringBuffer(256);
				sb.append("Poi time : ");
				sb.append(poiLocation.getTime());
				sb.append("\nerror code : ");
				sb.append(poiLocation.getLocType());
				sb.append("\nlatitude : ");
				sb.append(poiLocation.getLatitude());
				sb.append("\nlontitude : ");
				sb.append(poiLocation.getLongitude());
				sb.append("\nradius : ");
				sb.append(poiLocation.getRadius());
				if (poiLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
					sb.append("\naddr : ");
					sb.append(poiLocation.getAddrStr());
				}
				if (poiLocation.hasPoi()) {
					sb.append("\nPoi:");
					sb.append(poiLocation.getPoi());
				} else {
					sb.append("noPoi information");
				}
				System.out.println(sb.toString());
			}
		}
		/**
		 * 转换百度地图坐标
		 * 
		 * @param baiduLat
		 *            百度地图坐标 纬度
		 * @param baiduLon
		 *            百度地图坐标 经度
		 * @throws IOException
		 * @throws HWNetException
		 * @throws JSONException
		 */
		private void transBaidu(final double baiduLat, double baiduLon) {
			try{
			String bmapBase64Encode = "http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=%1$s&y=%2$s";
			RequestInfo req = new RequestInfo();
			RequestInfo.method = "GET";
			req.context = SiteActivity.this;
			req.requestUrl = String.format(bmapBase64Encode,
					String.valueOf(baiduLon), String.valueOf(baiduLat));
			// 就一个普通个的url请求封装成Client而已
			super.getDataFromServer(req, new DataCallback<String>() {
				@Override
				public void processData(String paramObject) {
					System.out.println("paramObject:" + paramObject);
					JSONObject object;
					Double lon1 = 0d;
					Double lat1 = 0d;
					try {
						object = new JSONObject(paramObject);
						System.out.println(object);
						lon1 = Double.parseDouble(new String(Base64.decode(object.getString("x"))));
						lat1 = Double.parseDouble(new String(Base64.decode(object.getString("y"))));
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("转换出来的百度坐标经度:" + lon1 + "纬度:" + lat1);
					// 这里的就是GPS坐标 经过下面算法转换 基本上合真实的GPS坐标相差无几
					gps_Lat = latitude * 2 - lat1;
					gps_Lon = longitude * 2 - lon1;
					System.out.println("算法转算后的百度坐标经度:" + gps_Lon + "纬度:" + gps_Lat);
				}

				@Override
				public void getDataFailed() {
					// 这里仅作演示，实际请求失败后怎么操作根据实际情况来看

				}

			}, SiteActivity.this);
			// 获取请求后数据
			}catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}
	
	@Override
	protected void loadViewLayout() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void findViewById() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void processLogic() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		int sensorType = event.sensor.getType();
		float[] values = event.values;
		if (sensorType == Sensor.TYPE_ACCELEROMETER) {
			/*
			 * // 现在检测时间 long currentUpdateTime = System.currentTimeMillis(); //
			 * 两次检测的时间间隔 long timeInterval = currentUpdateTime - lastUpdateTime;
			 * // 判断是否达到了检测时间间隔
			 * System.out.println(lastUpdateTime+"---"+currentUpdateTime
			 * +"---"+timeInterval); lastUpdateTime = currentUpdateTime; if
			 * (timeInterval < UPTATE_INTERVAL_TIME) return;
			 */
			if (Math.abs(values[0]) > 14 || Math.abs(values[1]) > 14
					|| Math.abs(values[2]) > 14) {
				System.out.println("手机摇动");
				mVibrator.vibrate(100);
				// SimpleDateFormat f = new SimpleDateFormat(
				// "yyyy-MM-dd HH:mm:ss E");
				// tv.setText(f.format(new Date()) + "手机摇动了...");
				mSensorManager.unregisterListener(SiteActivity.this);
				loadData();
			}
		}
	}
	private TextView getTextView() {
		TextView txtView = new TextView(SiteActivity.this);
		return txtView;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		mSensorManager.registerListener(this,
				mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		mSensorManager.unregisterListener(this);
		super.onStop();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		mSensorManager.unregisterListener(this);
		super.onPause();
	}
}
